<template>
    <div class="page-box mod-assign-attempt-page" v-loading="loading">
        <el-container>
            <el-header>
                <div class="assignment-info">
                    <router-link :to="{ name: 'course', params: { courseId: courseId } }">{{ $t('mod.assign.correct.link_1') }}{{ studentAssginInfo?.course_name }}</router-link>
                    <router-link
                        :to="{
                            name: 'assignNull',
                            params: {
                                assignId: studentAssginInfo?.id,
                                courseId: studentAssginInfo?.course_id,
                                unitId: studentAssginInfo?.unit_id,
                            },
                        }"
                    >
                        {{ $t('mod.assign.correct.link_2') }}{{ studentAssginInfo?.title }}
                    </router-link>
                    <router-link
                        :to="{
                            name: 'assignReport',
                            params: {
                                assignId: studentAssginInfo?.id,
                                courseId: studentAssginInfo?.course_id,
                                unitId: studentAssginInfo?.unit_id,
                            },
                        }"
                    >
                        {{ $t('mod.assign.correct.link_3') }}
                    </router-link>
                </div>
                <el-card shadow="hover">
                    <div class="user-box">
                        <div class="user-picture pic">
                            <img :src="student?.avatar_url" class="ele" v-if="student?.avatar_url" />
                            <el-icon size="20" color="#fff" v-else><User /></el-icon>
                        </div>
                        <div class="user-info">
                            <div class="user-name">{{ student?.last_name }} {{ student?.first_name }}</div>
                            <div class="user-email">{{ student?.email }}</div>
                        </div>
                        <div class="deadline" v-if="studentAssginInfo">{{ $t('mod.assign.correct.user_box.deadline') }}{{ formatLoginTime(studentAssginInfo.end_date) }}</div>
                    </div>
                </el-card>
                <div class="filter-box">
                    <el-icon @click="prevHandle" v-if="currentIndex > 0"><ArrowLeftBold /></el-icon>
                    <el-select v-model="filterStudentId" placeholder="Select" style="width: 240px" @change="switchStudentInfo">
                        <el-option v-for="student in studentList" :key="student.student_id" :label="`${student.last_name} ${student.first_name}`" :value="student.student_id" />
                    </el-select>
                    <el-icon @click="nextHandle" v-if="currentIndex < studentList.length - 1"><ArrowRightBold /></el-icon>

                    <el-button icon="Filter" @click="filterDialog = true" color="#F06423">{{ currentIndex + 1 }}/{{ studentList.length }}</el-button>
                </div>
            </el-header>
            <el-main :class="{ 'layout-1': defaultLayout === 1, 'layout-3': defaultLayout === 3 }">
                <div class="pdf-box">
                    <PdfView :fileUrl="studentAssginInfo?.submission.file_url" v-if="studentAssginInfo?.submission?.file_url" />
                </div>
                <div class="job-evaluation">
                    <div class="container">
                        <h3>{{ $t('mod.assign.correct.job_evaluation.tit_1') }}</h3>
                        <el-alert :title="$t(statusText)" type="success" :closable="false" />
                        <el-alert :title="$t(ratingStatusText)" type="success" :closable="false" />
                        <el-alert :title="remainingTimeText" type="warning" :closable="false" />
                        <!-- <el-alert title="學生不能編輯這一繳交的作業" type="error" :closable="false" /> -->
                        <div class="file-upload-submission">
                            <div class="file-time">
                                <a
                                    :href="studentAssginInfo?.submission?.similarity_link"
                                    class="file-name"
                                    v-if="studentAssginInfo?.submission?.file_url && studentAssginInfo?.submission?.similarity_link"
                                >
                                    <el-icon size="16" color="#4c4c4c"><Reading /></el-icon>
                                    <span>{{ studentAssginInfo?.submission?.file_url.split('/').pop() }}</span>
                                </a>
                                <div class="file-name" v-else>
                                    <el-icon size="16" color="#4c4c4c"><Reading /></el-icon>
                                    <span>{{ studentAssginInfo?.submission?.file_url ? studentAssginInfo?.submission?.file_url.split('/').pop() : '-' }}</span>
                                </div>
                                <div class="file-up-time" v-if="studentAssginInfo?.submission?.submission_time">{{ formatLoginTime(studentAssginInfo.submission.submission_time) }}</div>
                            </div>
                            <h4>{{ $t('mod.assign.correct.job_evaluation.submission.tit') }}</h4>
                            <table>
                                <tbody>
                                    <tr>
                                        <td width="120">{{ $t('mod.assign.correct.job_evaluation.submission.table_label_1') }}</td>
                                        <td>{{ studentAssginInfo?.submission?.similarity_status || '-' }}</td>
                                    </tr>
                                    <tr>
                                        <td width="120">{{ $t('mod.assign.correct.job_evaluation.submission.table_label_2') }}</td>
                                        <td>{{ studentAssginInfo?.submission?.similarity_per ? studentAssginInfo?.submission.similarity_per : '-' }}</td>
                                    </tr>
                                    <!-- <tr>
                                        <td width="120">報告：</td>
                                        <td>（一次性使用，有效期至 6:04 pm，請刷新瀏覽器以便再次查看報告。）</td>
                                    </tr>
                                    <tr>
                                        <td width="120">備註：</td>
                                        <td>Error in all files</td>
                                    </tr> -->
                                </tbody>
                            </table>
                            <p class="tips">*{{ $t('mod.assign.correct.job_evaluation.submission.tip') }}</p>
                        </div>
                        <h3>{{ $t('mod.assign.correct.job_evaluation.tit_2') }}</h3>
                        <el-form :model="gradeFrom" label-position="top">
                            <el-form-item :label="criteria.title" :prop="criteria.name" v-for="(criteria, index) in studentAssginInfo?.criteria" :key="index">
                                <el-radio-group v-model="gradeFrom.score_result[criteria.name].is_passed">
                                    <el-radio :value="0">{{ criteria.negative }}</el-radio>
                                    <el-radio :value="1">{{ criteria.positive }}</el-radio>
                                </el-radio-group>
                                <el-input v-model="gradeFrom.score_result[criteria.name].comment" :rows="5" type="textarea" placeholder="請輸入評語" />
                            </el-form-item>
                        </el-form>
                        <el-tag type="danger">{{ $t('mod.assign.correct.job_evaluation.con') }}{{ studentAssginInfo?.submission?.score }}</el-tag>
                        <h3>{{ $t('mod.assign.correct.job_evaluation.tit_3') }}</h3>
                        <RichTextEditor v-model="gradeFrom.teacher_comment" @update-richValue="gradeFrom.teacher_comment = $event" />
                    </div>
                </div>
            </el-main>
            <el-footer>
                <div></div>
                <div class="btn-list">
                    <el-checkbox v-model="gradeFrom.is_notice" label="通知學生" />
                    <el-button color="#f06423" @click="submitHandle">{{ $t('golbal.btn_text_1') }}</el-button>
                    <el-button color="#f06423" @click="nextSubmitHandle" v-if="currentIndex < studentList.length - 1">{{ $t('mod.assign.correct.btn_text_1') }}</el-button>
                    <el-button color="#f06423" @click="getStudentAssgin">{{ $t('mod.assign.correct.btn_text_2') }}</el-button>
                </div>
                <div class="change-layout-icon">
                    <el-button-group>
                        <el-button :class="{ active: defaultLayout === 1 }" @click="defaultLayout = 1"><img src="@/assets/img/layout-expand-right.svg" alt="" /></el-button>
                        <el-button :class="{ active: defaultLayout === 2 }" @click="defaultLayout = 2"><img src="@/assets/img/layout-default.svg" alt="" /></el-button>
                        <el-button :class="{ active: defaultLayout === 3 }" @click="defaultLayout = 3"><img src="@/assets/img/layout-expand-left.svg" alt="" /></el-button>
                    </el-button-group>
                </div>
            </el-footer>
        </el-container>

        <el-dialog v-model="filterDialog" :title="$t('mod.assign.correct.filter_dialog.tit')" width="400" class="mobile-dialog">
            <el-form>
                <el-form-item :label="$t('mod.assign.correct.filter_dialog.label')">
                    <el-select v-model="filterVal" placeholder="Select">
                        <el-option :label="$t('mod.assign.correct.filter_dialog.opt_1')" value="1" />
                        <el-option :label="$t('mod.assign.correct.filter_dialog.opt_2')" value="2" />
                        <el-option :label="$t('mod.assign.correct.filter_dialog.opt_3')" value="3" />
                        <el-option :label="$t('mod.assign.correct.filter_dialog.opt_4')" value="4" />
                    </el-select>
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button color="#F06423" @click="getStudentList" :loading="filterDialogLoading">{{ $t('golbal.btn_text_4') }}</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'

import AssignService from '@/api/assign'
import type { AssignReport, AssignInfo } from '@/types/assign'

import { formatLoginTime, goPage } from '@/utils/global'

import PdfView from '@/components/PdfView.vue'
import RichTextEditor from '@/components/RichTextEditor.vue'

import { useI18n } from 'vue-i18n'
import type { SupportedLocales } from '@/locales/i18n'
import type { MessageSchema } from '@/types/i18n'

const route = useRoute()
const router = useRouter()
const loading = ref(false)
const courseId = computed(() => Number(route.params.courseId)) // 课程id
const studentId = computed(() => Number(route.query.studentId))
const unitId = computed(() => Number(route.params.unitId))
const assignId = computed(() => Number(route.params.assignId))
const { t } = useI18n<{ message: MessageSchema }, SupportedLocales>()

// 页面信息
const studentAssginInfo = ref<AssignInfo>()
const statusText = computed(() => {
    if (studentAssginInfo.value?.submission) {
        switch (studentAssginInfo.value?.submission.submission_status) {
            case 1:
                return 'mod.assign.correct.job_evaluation.con_1'
            case 2:
                return 'mod.assign.correct.job_evaluation.con_2'
            case 3:
                return 'mod.assign.correct.job_evaluation.con_3'
            case 4:
                return 'mod.assign.correct.job_evaluation.con_4'
            default:
                return 'mod.assign.correct.job_evaluation.con_5'
        }
    } else {
        return 'mod.assign.correct.job_evaluation.con_5'
    }
})
const ratingStatusText = computed(() => {
    if (studentAssginInfo.value?.submission?.overall_status === 1) {
        return 'mod.assign.correct.job_evaluation.con_6'
    } else {
        return 'mod.assign.correct.job_evaluation.con_7'
    }
})
const remainingTimeText = computed(() => {
    if (!studentAssginInfo.value?.end_date) return '-'

    const endDate = new Date(studentAssginInfo.value?.end_date)
    const now = new Date()
    const diffTime = endDate.getTime() - now.getTime()
    if (diffTime >= 0) {
        const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24))
        const diffHours = Math.floor((diffTime % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60))
        return `${diffDays} ${t('mod.assign.correct.job_evaluation.con_8')} ${diffHours} ${t('mod.assign.correct.job_evaluation.con_9')}`
    } else {
        const _diffTime = diffTime * -1
        const _diffDays = Math.floor(_diffTime / (1000 * 60 * 60 * 24))
        const _diffHours = Math.floor((_diffTime % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60))
        return `${t('mod.assign.correct.job_evaluation.con_10')}${_diffDays} ${t('mod.assign.correct.job_evaluation.con_8')} ${_diffHours} ${t('mod.assign.correct.job_evaluation.con_9')}`
    }
})
function getStudentAssgin() {
    if (!student.value) student.value = studentList.value[0]
    AssignService.getByStudentId(courseId.value, student.value.student_id)
        .then(res => {
            studentAssginInfo.value = res
            gradeFrom.teacher_comment = studentAssginInfo.value.submission?.teacher_comment || ''
            gradeFrom.id = studentAssginInfo.value.submission?.id || 0
            if (studentAssginInfo.value.submission?.score_result) {
                studentAssginInfo.value.submission?.score_result.forEach(score => {
                    gradeFrom.score_result[score.name] = {
                        ...score,
                    }
                })
            } else {
                studentAssginInfo.value.criteria.forEach(criteria => {
                    gradeFrom.score_result[criteria.name] = {
                        is_passed: '',
                        comment: '',
                    }
                })
            }
        })
        .finally(() => {
            loading.value = false
        })
}

const studentList = ref<AssignReport[]>([])
const student = ref<AssignReport>()
const currentIndex = ref<number>(1)
function getStudentList() {
    filterDialog.value = false
    loading.value = true
    AssignService.list(courseId.value, { no_page: 1, type: filterVal.value })
        .then(res => {
            studentList.value = res.list

            if (!studentId.value) {
                console.log(1)
                student.value = studentList.value[0]
                currentIndex.value = 0
            } else {
                student.value = studentList.value.find(item => item.student_id === studentId.value) || studentList.value[0]
                currentIndex.value = studentList.value.findIndex(item => item.student_id === studentId.value)
            }
            student.value ? (filterStudentId.value = student.value.student_id) : ''
            getStudentAssgin()
        })
        .catch(() => {
            loading.value = false
        })
}
const prevHandle = () => {
    const index = studentList.value.findIndex(item => item.id === studentId.value)
    if (index > 0) {
        filterStudentId.value = studentList.value[index - 1].id
        currentIndex.value = index - 1
    }
}
const nextHandle = () => {
    const index = studentList.value.findIndex(item => item.id === studentId.value)
    if (index < studentList.value.length - 1) {
        filterStudentId.value = studentList.value[index + 1].id
        currentIndex.value = index + 1
    }
}

// 筛选
const filterDialog = ref(false)
const filterDialogLoading = ref(false)
const filterVal = ref()
const filterStudentId = ref<number>()
const switchStudentInfo = () => {
    student.value = studentList.value.find(item => item.student_id === filterStudentId.value)
    currentIndex.value = studentList.value.findIndex(item => item.student_id === filterStudentId.value)
}
watch(
    () => filterStudentId.value,
    () => {
        router.push({
            query: {
                studentId: filterStudentId.value,
            },
        })
    },
)

// 提交事件
const submitHandle = () => {
    loading.value = true
    AssignService.score(gradeFrom).finally(() => {
        loading.value = false
    })
}
const nextSubmitHandle = async () => {
    nextHandle()
    submitHandle()
}

// 布局
const defaultLayout = ref(2)

// 成绩
const gradeFrom = reactive<{ id: number; teacher_comment: string; score_result: any, is_notice: boolean }>({
    id: 0,
    score_result: {} as any,
    teacher_comment: '',
    is_notice: false,
})
watch(
    () => gradeFrom.score_result,
    () => {
        let score = 0
        for (const key in gradeFrom.score_result) {
            if (Object.prototype.hasOwnProperty.call(gradeFrom.score_result, key)) {
                const element = gradeFrom.score_result[key]
                if (element.is_passed) score++
            }
        }
        if (studentAssginInfo.value?.submission) studentAssginInfo.value.submission.score = score * 25
    },
    {
        deep: true,
    },
)

onMounted(() => {
    getStudentList()
})
</script>

<style scoped lang="less">
@import '@/assets/styles/variable.less';
.mod-assign-attempt-page {
    padding: 0;
    height: 100%;
    overflow: hidden;

    display: flex;
    flex-direction: column;

    .el-container {
        height: 100%;
        overflow: hidden;
    }

    .el-header {
        display: flex;
        align-items: center;
        justify-content: space-between;

        border-bottom: 1px solid rgba(0, 0, 0, 0.1);
        background-color: #f4f4f4;

        --el-header-padding: 20px 10vw;
        --el-header-height: auto;
        @media screen and (max-width: @vPad) {
            display: grid;
            grid-template-columns: 1fr;
            row-gap: 20px;
            --el-header-padding: 20px;
        }
        .assignment-info {
            display: flex;
            flex-direction: column;
            gap: 4px;
            a {
                font-size: 15px;
                display: block;
                color: #4c4c4c;
                line-height: 1.2;

                &:hover {
                    color: #f06423;
                }
            }
        }

        .el-card {
            --el-card-padding: 10px;

            .user-box {
                flex-wrap: wrap;

                .user-info {
                    align-items: stretch;
                    flex-direction: column;
                    gap: 4px;
                    color: #000;

                    .user-name {
                        font-size: 20px;
                        line-height: 1.2;
                    }

                    .user-email {
                        font-size: 12px;
                    }
                }

                .deadline {
                    width: 100%;
                    color: #000;
                    font-size: 12px;
                    text-align: right;
                }
            }
        }

        .filter-box {
            display: flex;
            align-items: center;
            gap: 10px;

            .el-icon {
                cursor: pointer;

                &:hover {
                    color: #f06423;
                }
            }

            .el-button {
                --el-button-hover-bg-color: #f064231a;
                --el-button-hover-border-color: #f064234d;
                --el-button-hover-text-color: #f06423;
            }
        }
    }

    .el-main {
        padding: 0;
        display: flex;
        width: 100%;
        height: 100%;
        overflow: hidden;
        @media screen and (max-width: @vPad) {
            display: grid;
            grid-template-columns: 1fr;
            row-gap: 20px;
        }
        &.layout-1 {
            .pdf-box {
                width: 0;
            }
            .job-evaluation {
                width: 100%;
            }
        }

        &.layout-3 {
            .pdf-box {
                width: 100%;
            }

            .job-evaluation {
                width: 0;
            }
        }

        .pdf-box {
            width: 70%;
            height: 100%;
            overflow: auto;
            transition: width 0.35s ease-in-out;
            @media screen and (max-width: @vPad) {
                width: 100%;
            }
        }

        .job-evaluation {
            border-left: 1px solid rgba(0, 0, 0, 0.125);
            width: 30%;
            transition: width 0.35s ease-in-out;
            height: 100%;
            overflow-y: auto;
            @media screen and (max-width: @vPad) {
                width: 100%;
            }
            .container {
                margin: 0 auto;
                padding: 0 15px 30px;
                background-color: #ffffff;
                max-width: 800px;

                h3 {
                    margin-top: 30px;
                    margin-bottom: 18px;
                    font-size: 24px;
                    font-weight: normal;
                    line-height: 1.2;
                    color: #000;
                }

                .el-alert {
                    margin-bottom: 6px;
                }

                .file-upload-submission {
                    margin-top: 15px;
                    padding: 15px;
                    background-color: #f1f1f1;

                    .file-time {
                        margin-bottom: 20px;

                        display: flex;
                        align-items: center;
                        justify-content: space-between;

                        .file-name {
                            color: #000;

                            display: flex;
                            align-items: center;
                            gap: 6px;
                        }

                        .file-up-time {
                            font-size: 12px;
                            color: #000;
                        }
                    }

                    h4 {
                        margin-bottom: 8px;
                        color: #000;
                        font-size: 20px;
                        line-height: 1.2;
                        font-weight: normal;
                    }

                    table {
                        width: 100%;
                        border: 1px solid #dee2e6;
                        border-collapse: collapse;
                        border-spacing: 0;

                        tr {
                            background-color: #f2f2f2;

                            &:nth-child(2n) {
                                background-color: #fff;
                            }

                            td {
                                border: 1px solid #dee2e6;
                                padding: 6px;
                                color: #212529;
                                font-size: 12px;
                                line-height: 1.6;

                                &:first-child {
                                    color: #000;
                                }
                            }
                        }
                    }

                    p {
                        margin-top: 6px;
                        color: #000;
                        font-size: 12px;
                    }
                }

                :deep(.el-form) {
                    .el-form-item {
                        .el-form-item__label {
                            font-size: 18px;
                            font-weight: bold;
                        }
                    }
                    .el-radio {
                        width: 100%;
                    }
                }

                :deep(.el-textarea) {
                    margin-top: 10px;
                }

                .el-tag {
                    position: sticky;
                    bottom: 10px;
                    z-index: 2;
                }

                :deep(.ck-editor) {
                    width: 100%;

                    .ck-editor__main {
                        .ck-content {
                            min-height: 350px;
                            max-height: 600px;
                        }
                    }
                }
            }
        }
    }

    .el-footer {
        border-top: 1px solid rgba(0, 0, 0, 0.1);
        background-color: #f4f4f4;

        display: flex;
        align-items: center;
        justify-content: space-between;

        .btn-list {
            display: flex;
            align-items: center;

            .el-checkbox {
                margin-right: 15px;
            }

            .el-button {
                color: #fff;
            }
        }

        .change-layout-icon {
            .el-button {
                &:hover {
                    border: 1px solid rgba(240, 100, 35, 0.3);
                    background-color: rgba(240, 100, 35, 0.1);
                }

                &.active {
                    border: 1px solid #f06423;
                    background-color: #f06423;

                    img {
                        filter: brightness(0) invert(1);
                    }
                }
            }
        }
    }
}
</style>
